// src/router/index.ts
import { createRouter, createWebHistory, type NavigationGuardNext, type RouteLocationNormalized } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
// @ts-ignore
import DataStatistics from '../views/DataStatistics.vue'
import ScoringData from '../views/Statistics/ScoringData.vue'
import OrderManagement from '../views/Statistics/OrderManagement.vue'
import ErrorView from '../views/ErrorView.vue'

// 全局错误处理函数
export const handleError = (router: any, error: { message?: string; code?: string | number; stack?: string; type?: string }) => {
  console.error('全局错误:', error)
  
  // 构建错误参数
  const errorParams: Record<string, string> = {
    type: 'error',
  }
  
  // 根据错误类型设置不同的参数
  if (error.message) {
    errorParams.message = error.message
  }
  
  if (error.code) {
    errorParams.code = String(error.code)
  }
  
  // 在开发环境下传递堆栈信息
  if (import.meta.env.DEV && error.stack) {
    errorParams.stack = error.stack
  }
  
  // 跳转到错误页面
  router.push({
    path: '/error',
    query: errorParams
  })
}

const routes: Array<RouteRecordRaw> = [
  { path: '/', name: 'Home', component: Home },
  { path: '/login', name: 'Login', component: Login },
  { path: '/error', name: 'Error', component: ErrorView },
  // 捕获所有未匹配的路由，指向错误页面
  { path: '/:pathMatch(.*)*', name: 'NotFound', component: ErrorView },
  // 重定向到 DataStatistics 子路由
  { 
    path: '/:page(ScoringData|AnalysisProfit|OrderManagement)', 
    name: 'StatisticsPageRedirect', 
    redirect: to => `/DataStatistics/${to.params.page}`
  },
  // 主路由与嵌套路由结构
  { 
    path: '/DataStatistics', 
    name: 'DataStatistics', 
    component: DataStatistics,
    children: [
      { path: 'ScoringData', name: 'ScoringData', component: ScoringData },
      { path: 'OrderManagement', name: 'OrderManagement', component: OrderManagement },
      // 默认重定向到评分数据页面
      { path: '', redirect: 'OrderManagement', name: 'DataStatisticsDefault' }
    ]
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 暂时禁用登录验证，让应用直接进入首页
router.beforeEach((_to: RouteLocationNormalized, _from: RouteLocationNormalized, next: NavigationGuardNext) => {
  // 直接允许所有路由访问
  next()
})

export default router
